package com.java1234.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java1234.entity.Answer;
import com.java1234.entity.ExamDetail;
import com.java1234.entity.ExamQuestion;
import com.java1234.entity.Question;
import com.java1234.service.AnswerService;
import com.java1234.service.ExamDetailService;
import com.java1234.mapper.ExamDetailMapper;
import com.java1234.service.ExamQuestionService;
import com.java1234.service.QuestionService;
import com.java1234.util.ScoreCalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 86195
* @description 针对表【exam_detail(答题详情)】的数据库操作Service实现
* @createDate 2024-12-05 14:14:03
*/
@Service
public class ExamDetailServiceImpl extends ServiceImpl<ExamDetailMapper, ExamDetail>
    implements ExamDetailService{
    @Autowired
    private ExamDetailMapper examDetailMapper;

    @Autowired
    private ExamQuestionService examQuestionService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ScoreCalculator scoreCalculator;

    @Autowired
    private AnswerService answerService;

    @Override
    public void saveExamDetails(Long examHistoryId, Map<String, Object> userAnswers, List<ExamQuestion> examQuestions) {
        for (ExamQuestion examQuestion : examQuestions) {
            Question question = questionService.getById(examQuestion.getQuestionId());
            String questionIdStr = String.valueOf(question.getId());
            Object userAnswer = userAnswers.get(questionIdStr);

            // 获取正确答案
            List<Answer> correctAnswers = answerService.list(new QueryWrapper<Answer>()
                    .eq("question_id", question.getId())
                    .eq("is_answer", true));
            String correctAnswer = correctAnswers.stream()
                    .map(Answer::getAnswerContent)
                    .collect(Collectors.joining(", "));

            ExamDetail examDetail = new ExamDetail();
            examDetail.setExamHistoryId(examHistoryId);
            examDetail.setQuestionId(question.getId());
            examDetail.setUserAnswer(userAnswer != null ? userAnswer.toString() : "");
            examDetail.setCorrectAnswer(correctAnswer);
            examDetail.setIsCorrect(scoreCalculator.isCorrect(question, userAnswer, correctAnswers));
            examDetail.setScore(scoreCalculator.calculateScore(question, userAnswer));

            this.save(examDetail);
        }
    }

    @Override
    public List<ExamDetail> getExamDetailsByExamHistoryId(Long examHistoryId) {
        return examDetailMapper.selectList(new QueryWrapper<ExamDetail>().eq("exam_history_id", examHistoryId));
    }
}



